package com.timberwood.model.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.Session;

import com.timberwood.model.entity.News;
import com.timberwood.util.HibernateUtil;

public class NewDAO {
	

	private Session session;
	private Transaction transaction;
	public NewDAO() {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		transaction= session.beginTransaction();
	}
	
	
	
	//method lấy về danh sách tin tức theo từng lọai
	@SuppressWarnings("unchecked")
	public List<News> sleNewByType(String typeNew){
		List<News> listnews=null;	
		try {
			listnews=(List<News>) session.getNamedQuery("sleNewsByType").setString("typeNew", typeNew).list();
		} catch (HibernateException he) {
			transaction.rollback();
			he.printStackTrace();
		}
		transaction.commit();
		return listnews;
	}
	
	//method lấy chi tiết của tin tức khi biết mã tin tức
	public News sleNewByNid(int newId){
		News objnew=null;
		try {
			objnew=(News)session.getNamedQuery("getNewsByType").setInteger("newId", newId).uniqueResult();
		} catch (HibernateException he) {
			transaction.rollback();
			he.printStackTrace();
		}
		transaction.commit();
		return objnew;
	}
	
	
	//method thêm mới một tin tức
	public boolean insertNew(News objNew){
		boolean status;
		try {
			session.save(objNew);
			status=true;
		} catch (HibernateException he) {
			status=false;
			transaction.rollback();
			he.printStackTrace();
		}
		transaction.commit();
		return status;
	}
	
	
	//method cập nhật một tin tức
	public boolean updateNew(News objNew){
		boolean status;
		try {
			session.update(objNew);
			status=true;
		} catch (HibernateException he) {
			status=false;
			transaction.rollback();
			he.printStackTrace();
		}
		transaction.commit();
		return status;
	}
	
	//method xóa một tin tức
	public boolean deleteNew(int newId){
		boolean status;
		try {
			session.getNamedQuery("deleteNew").setInteger("newID", newId).executeUpdate();
			status=true;
		}catch (HibernateException he) {
			status=false;
			transaction.rollback();
			he.printStackTrace();
		}
		transaction.commit();
		return status;		
	}
	
	
	
	
	
	

}
